package middlewares

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"mycms/global"
	"mycms/model/common/response"
	"mycms/service/common"
	"mycms/utils"
	"strings"
)

// 访问权限拦截器
func CasbinHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		//	获取请求的PATH
		obj := c.Request.URL.Path

		// 获取请求方法
		act := c.Request.Method

		// 获取用户的角色
		sub := utils.GetUserRole(c)
		subArr := strings.Split(sub, ",") //	分隔成字符串切片

		e := common.CasbinServiceApp.Casbin()

		if global.CONFIG.System.Env == "develop" {
			//	开发环境，跳过权限验证
			c.Next()
		} else {
			// 循环用户所有角色，判断策略中是否存在
			fmt.Println("路径，方法", obj, act)
			isPass := false
			for _, val := range subArr {
				fmt.Println("角色ID: ", val)
				success, _ := e.Enforce(val, obj, act)
				fmt.Println("是否通过: ", success)

				//	匹配到权限则跳出循环
				if success {
					isPass = true
					break
				}
			}
			fmt.Println(isPass)
			if isPass {
				c.Next()
			} else {
				response.FailWithDetailed(gin.H{}, "权限不足", c)
				c.Abort()
				return
			}

		}
	}
}
